import React from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { Dashboard } from '@/pages/Dashboard/Dashboard';
import { useDataSync } from '@/hooks/core/useDataSync';
import { ToastContainer } from '@/components/ui/Toast';
import { TooltipProvider } from '@/components/ui/Tooltip';
import { queryClient } from '@/lib/queryClient';
import '@/index.css';
import { initStorageMode } from '@/config/storageMode';
import {initExtensionEnv} from '@/lib/extensionEnv';

// Dashboard应用根组件
// 包含主要功能和全局组件
const DashboardApp: React.FC = () => {
  // 统一数据同步：初始化 + 存储变化监听（仅 Preferences）
  useDataSync();

  return (
    <QueryClientProvider client={queryClient}>
      <TooltipProvider delayDuration={300} skipDelayDuration={100}>
        {/* 主要Dashboard页面 */}
        <Dashboard />

        {/* 全局Toast通知容器 */}
        <ToastContainer />
      </TooltipProvider>

      {/* 开发环境显示 React Query DevTools */}
      {import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
    </QueryClientProvider>
  );
};

// 启动函数：避免顶层 await，确保初始化完成后再渲染
(async function bootstrap() {
  // 优先缓存扩展ID，满足“加载即得”
  initExtensionEnv();
  await initStorageMode();

  const rootElement = document.getElementById('root');
  if (!rootElement) throw new Error('根元素#root未找到，请检查dashboard.html文件');

  const root = createRoot(rootElement);
  root.render(<DashboardApp />);
})();
